package com.mutiplethread.demo;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class LockCondition {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();//锁
        Condition empty = lock.newCondition();//空情况
        Condition full = lock.newCondition();//满情况
        AtomicInteger num = new AtomicInteger(5);

        //消费者
        Thread cus = new Thread(() -> {
            while (true) {
                lock.lock();//要在try块外 上锁（确定一定上锁 try里上锁 遇到异常跳出就不会锁住了）
                try {
                    while (num.get() == 0) {
                        empty.await();//此时为空 空情况等待
                    }
                    System.out.println(Thread.currentThread().getName() + "消费了" + num);
                    num.getAndDecrement();
                    full.signal();//此时已经消费了1个 所以把通知满情况等待的线程

                } catch (InterruptedException e) {

                } finally {
                    lock.unlock();//要在finally里 解锁
                }
            }


        }, "消费者");
        Thread pro = new Thread(() -> {
            while (true) {
                lock.lock();
                try {
                    while (num.get() == 10) {
                        full.await();//此时已满 满情况等待
                    }
                    System.out.println(Thread.currentThread().getName() + "生产了" + num);
                    num.getAndIncrement();
                    empty.signal();//生产了一个 通知空情况等待的线程

                } catch (InterruptedException e) {

                } finally {
                    lock.unlock();
                }
            }
        }, "生产者");
        cus.start();
        pro.start();

    }
}
